package com.eqdd.yiqidian.widget;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;


import com.eqdd.library.percentUtil.WindowUtil;
import com.eqdd.yiqidian.CalendarLayoutCustom;
import com.eqdd.yiqidian.MonthLayoutCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.bean.rebuild.CalendarBean;
import com.eqdd.yiqidian.bean.rebuild.MemoListBean;
import com.eqdd.yiqidian.utils.juster.MoveEffectAdjuster;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lvzhihao on 17-5-16.
 */

public class CalendarViewGroup extends RelativeLayout {

    private CalendarLayoutCustom inflate;
    private Map<Integer, MonthLayoutCustom> viewMap = new HashMap<>();
    private Map<Integer, List<CalendarBean>> dataMap = new HashMap<>();
    private Map<Integer, RecyclerView.Adapter> adapterMap = new HashMap<>();
    private LayoutInflater layoutInflater;
    private Context context;

    public CalendarViewGroup(Context context) {
        super(context);
    }

    public CalendarViewGroup(final Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
        inflate = DataBindingUtil.inflate(layoutInflater, R.layout.calendar_layout, this, true);
    }

    public interface OnAdapter {
        RecyclerView.Adapter adpter(RecyclerView recyclerView);

//        void data(int position, Date date, CalendarViewGroup calendarViewGroup);

        void notify(RecyclerView.Adapter adapter, List<CalendarBean> data);
    }

    public void refreshDate(int position, List<CalendarBean> data) {
        if (inflate.viewPager.getCurrentItem() == position) {
            ViewGroup.LayoutParams layoutParams = inflate.viewPager.getLayoutParams();
            if (data.size() > 35) {

                layoutParams.height = WindowUtil.csw * 430 / WindowUtil.width;
            } else {
                layoutParams.height = WindowUtil.csw * 360 / WindowUtil.width;

            }
            inflate.viewPager.setLayoutParams(layoutParams);
        }
        dataMap.put(position, data);
        onAdapter.notify(adapterMap.get(position), dataMap.get(position));
    }

    OnAdapter onAdapter;
    OnMonthChangeListener monthChangeListener;

    public void setMonthChangeListener(OnMonthChangeListener monthChangeListener) {
        this.monthChangeListener = monthChangeListener;
    }

    public void setOnAdapter(OnAdapter onAdapter) {
        setAdapter();
        this.onAdapter = onAdapter;
    }

    public interface OnMonthChangeListener {
        void month(Date date, List<CalendarBean> data);
    }

    public void resume() {
        inflate.stvToday.startAnim();
    }

    public void pause() {
        inflate.stvToday.stopAnim();

    }

    private void setAdapter() {
        inflate.stvToday.setAdjuster(new MoveEffectAdjuster())
                .setAutoAdjust(true)
                .startAnim();
        inflate.stvToday.setOnClickListener(v -> {
            int sponce = inflate.viewPager.getCurrentItem() - Integer.MAX_VALUE / 2;
            if (sponce > 0) {
                for (int i = inflate.viewPager.getCurrentItem() - 1; i >= Integer.MAX_VALUE / 2; i--) {
                    inflate.viewPager.setCurrentItem(i);
                }
            } else {
                for (int i = inflate.viewPager.getCurrentItem() + 1; i <= Integer.MAX_VALUE / 2; i++) {
                    inflate.viewPager.setCurrentItem(i);
                }
            }
            updateView(Integer.MAX_VALUE / 2);
        });
        inflate.viewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return Integer.MAX_VALUE;
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public Object instantiateItem(ViewGroup container, final int position) {
                System.out.println(position);
                MonthLayoutCustom view = viewMap.get(position);
                Calendar ca = Calendar.getInstance();
                Date date = new Date();
                ca.setTime(date);
                ca.add(Calendar.MONTH, position - (Integer.MAX_VALUE / 2));
                if (view == null) {
                    MonthLayoutCustom monthLayoutCustom = DataBindingUtil.inflate(layoutInflater, R.layout.viewpager_layout, null, false);
                    monthLayoutCustom.recyclerView.setLayoutManager(new GridLayoutManager(context, 7));
                    monthLayoutCustom.recyclerView.setHasFixedSize(true);
                    RecyclerView.Adapter adapter = onAdapter.adpter(monthLayoutCustom.recyclerView);
                    monthLayoutCustom.recyclerView.setAdapter(adapter);
                    viewMap.put(position, monthLayoutCustom);
                    adapterMap.put(position, adapter);
                    dataMap.put(position, convertData(ca.getTime()));
//                    onAdapter.data(position, ca.getTime(), CalendarViewGroup.this);
                } else {
                    viewMap.get(position).recyclerView.setAdapter(adapterMap.get(position));
                }
//                onAdapter.notify(adapterMap.get(position), dataMap.get(position));
                container.addView(viewMap.get(position).getRoot());
                return viewMap.get(position).getRoot();

            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(viewMap.get(position).getRoot());
            }

        });
        updateView(Integer.MAX_VALUE / 2);
        inflate.ivPrevious.setOnClickListener(v -> {
            inflate.viewPager.setCurrentItem(inflate.viewPager.getCurrentItem() - 1);
            updateView(inflate.viewPager.getCurrentItem());
        });
        inflate.ivNext.setOnClickListener(v -> {
            inflate.viewPager.setCurrentItem(inflate.viewPager.getCurrentItem() + 1);
            updateView(inflate.viewPager.getCurrentItem());
        });
        inflate.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                updateView(inflate.viewPager.getCurrentItem());
                if (monthChangeListener != null) {
                    Calendar ca = Calendar.getInstance();
                    ca.setTime(new Date());
                    ca.add(Calendar.MONTH, position - (Integer.MAX_VALUE / 2));
                    monthChangeListener.month(ca.getTime(), dataMap.get(position));
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        inflate.viewPager.setCurrentItem(Integer.MAX_VALUE / 2);
    }

    public void refresh(List<CalendarBean> data) {
        int currentItem = inflate.viewPager.getCurrentItem();

        ViewGroup.LayoutParams layoutParams = inflate.viewPager.getLayoutParams();
        if (data.size() > 35) {
            layoutParams.height = WindowUtil.csw * 430 / WindowUtil.width;
        } else {
            layoutParams.height = WindowUtil.csw * 360 / WindowUtil.width;
        }
        inflate.viewPager.setLayoutParams(layoutParams);
        onAdapter.notify(adapterMap.get(currentItem), data);
    }

    private void updateView(int position) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        ca.add(Calendar.MONTH, position - (Integer.MAX_VALUE / 2));
        SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月");
        inflate.tvDate.setText(sf.format(ca.getTime()));
    }

    public List<CalendarBean> convertData(Date date) {
        ArrayList<CalendarBean> calendars = new ArrayList<>();

        Calendar current = Calendar.getInstance();
        current.setTime(new Date());//获取当前日期

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int month = calendar.get(Calendar.MONTH);//获取月份

        calendar.set(Calendar.DAY_OF_MONTH, 1);//设置月份第一天


        int minimalDaysInFirstWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;//月份第一天是星期几

        calendar.add(Calendar.DATE, -minimalDaysInFirstWeek);


        Calendar calendarLast = Calendar.getInstance();
        calendarLast.setTime(date);
        int actualMaximum = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);


        calendarLast.set(Calendar.DAY_OF_MONTH, actualMaximum);
        int lastDayofWeek = calendarLast.get(Calendar.DAY_OF_WEEK);
        calendarLast.add(Calendar.DATE, 7 - lastDayofWeek);
        System.out.println(calendarLast);
        while (calendar.getTime().getTime() <= calendarLast.getTime().getTime()) {
            CalendarBean calendarBean = new CalendarBean();
            Calendar temp = Calendar.getInstance();
            temp.setTime(calendar.getTime());
            calendarBean.setCalendar(temp);
            calendarBean.setToday(getDay(current) == getDay(temp));
            calendarBean.setInMonth(month == temp.get(Calendar.MONTH));
            calendars.add(calendarBean);
            calendar.add(Calendar.DATE, 1);
        }
        return calendars;
    }

    public List<CalendarBean> convertData(Date date, List<CalendarBean> calendas) {
        ArrayList<CalendarBean> calendars = new ArrayList<>();

        Calendar current = Calendar.getInstance();
        current.setTime(new Date());//获取当前日期

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int month = calendar.get(Calendar.MONTH);//获取月份

        calendar.set(Calendar.DAY_OF_MONTH, 1);//设置月份第一天


        int minimalDaysInFirstWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;//月份第一天是星期几

        calendar.add(Calendar.DATE, -minimalDaysInFirstWeek);


        Calendar calendarLast = Calendar.getInstance();
        calendarLast.setTime(date);
        int actualMaximum = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);


        calendarLast.set(Calendar.DAY_OF_MONTH, actualMaximum);
        int lastDayofWeek = calendarLast.get(Calendar.DAY_OF_WEEK);
        calendarLast.add(Calendar.DATE, 7 - lastDayofWeek);
        System.out.println(calendarLast);
        while (calendar.getTime().getTime() <= calendarLast.getTime().getTime()) {
            CalendarBean calendarBean = null;
            for (int i = 0; i < calendas.size(); i++) {
                if (calendas.get(i).getCalendar().get(Calendar.DAY_OF_YEAR) == calendar.get(Calendar.DAY_OF_YEAR)) {
                    MemoListBean memoListBean = new MemoListBean();
                    memoListBean.setEvent(true);
                    calendarBean = memoListBean;
                    break;

                }
            }
            if (calendarBean == null) {
                calendarBean = new CalendarBean();
            }
            Calendar temp = Calendar.getInstance();
            temp.setTime(calendar.getTime());
            calendarBean.setCalendar(temp);
            calendarBean.setToday(getDay(current) == getDay(temp));
            calendarBean.setInMonth(month == temp.get(Calendar.MONTH));
            calendars.add(calendarBean);
            calendar.add(Calendar.DATE, 1);
        }
        return calendars;
    }

    public CalendarViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private int getDay(Calendar calendar) {
        return (int) (calendar.getTime().getTime() / (1000 * 60 * 60 * 24));
    }

}
